package org.mymail.mail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

// Referenced classes of package org.mymail.mail:
//            PopMailSession, MailFwdType, UpdateSubscribers

public class ReadMail
{
	static Logger log = Logger.getLogger(ReadMail.class);

	public static void main(String args[])
    {
        readMail();
    }

    public static void readMail()
    {
    	//PropertyConfigurator.configure("config/log4j.properties");
        Session session = (new PopMailSession()).createSession();
        try
        {
            Store store = session.getStore("pop3");
            store.connect("pop.gmail.com", "sharath.ravindran2@gmail.com", "uvce2005.2005");
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);
            Message m[] = folder.getMessages(108,110);
            Date yesterdaysDate = getYesterDaysDate();
            for(int i = 0; i < m.length; i++)
            {
                String subject = m[i].getSubject();
                javax.mail.Address a2[] = m[i].getFrom();
                InternetAddress ia = (InternetAddress)a2[0];
                String from  = ia.getAddress();
                System.err.println("Message Number : "+m[i].getMessageNumber());
                if (m[i].getSentDate().after(yesterdaysDate)
						&& subject.contains("Unsubscribe Me - ")) {
					String service = subject.substring(
							subject.indexOf("-") + 2, subject.length());
					int mailFwdType = MailFwdType.getIntFromString(service);
					
					/*System.err.println((new StringBuilder("Mail addr : "))
							.append(a2[0]).toString());*/
					UpdateSubscribers.removeSubscriber(a2[0], mailFwdType);
				} else if (m[i].getSentDate().after(yesterdaysDate)
						&& subject.contains("Subscribe-Friends")) {
					ArrayList<SubscriberDetails> subscriberDet = new ArrayList<SubscriberDetails>();
					try {
						
						m[i].writeTo(System.out);
						BufferedReader in = new BufferedReader(new InputStreamReader(m[i].getInputStream()));
				        String str = "";
				        while (str != null) {
				            str = in.readLine();
				            if(str.startsWith("name:"))
				            {
				            	String name = str.substring(4);
				            	String str2 = in.readLine();
				            	String mailId = str2.substring(7);
				            	subscriberDet.add(new SubscriberDetails(name,mailId,from));
				            }
				        }
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
            }
            
            folder.close(true);
            store.close();
            session = null;
        }
        catch(NoSuchProviderException e)
        {
            e.printStackTrace();
        }
        catch(MessagingException e)
        {
            e.printStackTrace();
        }
    }

    private static Date getYesterDaysDate()
    {
        Calendar cal = new GregorianCalendar();
        cal.add(5, -1);
        Date date = cal.getTime();
        return date;
    }
}